package j.quartz.shiro.realm;

import j.quartz.zdao.data.SysDataConst;
import j.quartz.zdao.entity.IUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class JquartzRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(JquartzRealm.class);

    /**
     * 为用户授予角色和权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        IUser user = (IUser) principalCollection.getPrimaryPrincipal();
        LOGGER.info("IUser : {}", user);
        // SysUserUtil 封装获取当前用户信息
        authorizationInfo.setRoles((Set<String>) SysDataConst.DATA_MAP.get("roles"));
        // 获取允许用户的菜单编码，将菜单编码作为授权内容
        authorizationInfo.setStringPermissions((Set<String>) SysDataConst.DATA_MAP.get("perms"));
        return authorizationInfo;
    }

    /**
     * 登录验证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String) authenticationToken.getPrincipal();
        Object password = authenticationToken.getCredentials();
        LOGGER.info("username : {}", username);
        LOGGER.info("password : {}", password);

        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        IUser user = (IUser) SysDataConst.DATA_MAP.get("root");

        LOGGER.info("----->>user=" + user);
        if (user == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, // 用户名
                user.getPassword(), // 数据库查询的加密后密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
                getName()  //realm name
        );

        Subject subject = SecurityUtils.getSubject();
        IUser user1 = (IUser) subject.getPrincipal();
        return authenticationInfo;
    }

}
